package com.oktest.measure.ui.dialog

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import com.cali.libcore.dialog.alertdialog.AlertDialog
import com.oktest.measure.R
import com.oktest.measure.kt.screenWidth
import kotlinx.android.synthetic.main.measure_dialog_base_layout.view.*

/**
 * @Author HaoXin
 * @Date 2020/12/1
 */
class BaseDialogHelper(context: Context){
    private val contentView by lazy {
        View.inflate(context, R.layout.measure_dialog_base_layout, null).also {
            it.tvCancel.setOnClickListener {
                alertDialog.dismiss()
            }
            it.tvConfirm.setOnClickListener {
                if (onConfirm()) {
                    alertDialog.dismiss()
                }
            }
        }
    }

    private val frameLayout by lazy {
        alertDialog.getView<FrameLayout>(R.id.contentLayout)
    }

    private val title by lazy {
        alertDialog.getView<TextView>(R.id.tvDialogTitle)
    }

    var onDismiss: () -> Unit = {}
    var onConfirm: () -> Boolean = { false }

    private var alertDialog: AlertDialog = AlertDialog.Builder(context)
            .addDefaultAnimation()
            .setContentView(contentView)
            .setWidthAndHeight(context.screenWidth() - 160, ViewGroup.LayoutParams.WRAP_CONTENT)
            .setDim(0.3f)
            .create().also {
                it?.setOnDismissListener {
                    onDismiss()
                }
            }

    fun show(view: View, title: String) {
        view.parent?.apply {
            this as ViewGroup
            this.removeAllViews()
        }
        this.title.text = title
        frameLayout.addView(view)
        alertDialog.show()
    }

    fun dismiss() {
        alertDialog.dismiss()
    }
}